package com.ruoyi.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;





/**
 * ClassName:SignUtils
 * Function: 签名用的工具箱
 * Date:     2014-6-27 下午3:22:33 
 * @author    
 */
public class SignUtils {
    private static final Logger logger = LoggerFactory.getLogger(SignUtils.class);

    public static void main(String[] args) throws ParseException {
			SignUtils signUtils=new SignUtils();
			boolean s= checkParam(signUtils.hh(), "tlfsez85d94595uw6z1zs2tk2ivl5afp");//商户私钥
		    String aa = "2022-01-16 23:45:25";
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Date sd1=df.parse(aa);
        logger.info(sd1.before(new Date())+"");


        logger.info(s+"");
    }
	
	
	
	 public Map<String, String> hh(){
	 	   Map<String, String> map = new HashMap<String, String>();
	 	   map.put("service", "pay.alipay.wappay");//接口类型
	 	   map.put("version", "1.0");//版本号
	 	   map.put("charset", "UTF-8");//字符集
	 	   map.put("sign_type", "MD5");//签名方式
	 	   map.put("merchant_id", "7451842171");//商户号
	 	   map.put("out_trade_no", "d11"); //商户订单号
	 	   map.put("goods_desc", "zheshiceshi");//商品描述
	 	   map.put("attach", "zheshiceshi");//附加信息
	 	   map.put("total_amount", "10");//总金额
	 	   map.put("notify_url", "http://www.shangxinshuntong.com:1818/Pay_TLZFBH_notifyurl.html");//通知地址(不知道)
	 	   map.put("return_url", "http://www.shangxinshuntong.com:1818/Pay_TLZFBH_callbackurl.html");//前台地址（同步ok）
	 	   map.put("nonce_str", "4lSN5P8y9QSciCpy"); //随机字符串
	 	   map.put("sign", "C3C0A293F9199E5E93028AD1487A123D");//签名
	 	   return map;
	    }

    /** <一句话功能简述>
     * <功能详细描述>验证返回参数
     * @param params
     * @param key
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static boolean checkParam(Map<String,String> params,String key){
        boolean result = false;
        if(params.containsKey("sign")){
            String sign = params.get("sign");
            params.remove("sign");
            StringBuilder buf = new StringBuilder((params.size() +1) * 10);
            SignUtils.buildPayParams(buf,params,false,"");
            String preStr = buf.toString();
            String signRecieve = MD5Util.stringMD5(preStr+ "&key=" + key);

            logger.info(preStr+"&key=" + key+" 生成sign............"+signRecieve);
            
            
            result = sign.equalsIgnoreCase(signRecieve);
        }
        return result;
    }   
    /**
     * 过滤参数
     * @author  
     * @param sArray
     * @return
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<String, String>(sArray.size());
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }
    
    public static Map<String, String> paraFilterByObject(Map<String, Object> sArray) {
        Map<String, String> result = new HashMap<String, String>(sArray.size());
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = String.valueOf(sArray.get(key));
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }
    
    /** <一句话功能简述>
     * <功能详细描述>将map转成String
     * @param payParams
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static String payParamsToString(Map<String, String> payParams){
        return payParamsToString(payParams,false);
    }
    
    public static String payParamsToString(Map<String, String> payParams,boolean encoding){
        return payParamsToString(new StringBuilder(),payParams,encoding);
    }
    /**
     * @author 
     * @param payParams
     * @return
     */
    public static String payParamsToString(StringBuilder sb,Map<String, String> payParams,boolean encoding){
        buildPayParams(sb,payParams,encoding,"");
        return sb.toString();
    }
    
    /**
     * @author 
     * @param payParams
     * @return
     */
    public static void buildPayParams(StringBuilder sb,Map<String, String> payParams,boolean encoding,String paramLowType){
        List<String> keys = new ArrayList<String>(payParams.keySet());
        Collections.sort(keys);
        for(String key : keys){
            if (payParams.get(key) == null || String.valueOf(payParams.get(key)).equals("")) {
                continue;
            }
            if(StringUtils.isNotBlank(paramLowType)){
                if(paramLowType.equalsIgnoreCase("up")){
                    sb.append(key.toUpperCase()).append("=");

                }else{
                    sb.append(key.toLowerCase()).append("=");
                }
            }else{
                sb.append(key).append("=");
            }
            if(encoding){
                sb.append(urlEncode(String.valueOf(payParams.get(key))));
            }else{
                sb.append(String.valueOf(payParams.get(key)));
            }
            sb.append("&");
        }
        sb.setLength(sb.length() - 1);
    }

    /**
     * @author
     * @param payParams
     * @return
     */
    public static void buildPayParams(StringBuilder sb,Map<String, String> payParams,boolean encoding){
        List<String> keys = new ArrayList<String>(payParams.keySet());
        Collections.sort(keys);
        for(String key : keys){
            if (payParams.get(key) == null || String.valueOf(payParams.get(key)).equals("")) {
                continue;
            }
            sb.append(key).append("=");
            if(encoding){
                sb.append(urlEncode(String.valueOf(payParams.get(key))));
            }else{
                sb.append(String.valueOf(payParams.get(key)));
            }
            sb.append("&");
        }
        sb.setLength(sb.length() - 1);
    }


    /**
     * @author
     * @param payParams
     * @return
     */
    public static void buildPayParamsObj(StringBuilder sb,Map<String, Object> payParams,boolean encoding){
        List<String> keys = new ArrayList<String>(payParams.keySet());
        Collections.sort(keys);
        for(String key : keys){
            if (payParams.get(key) == null || String.valueOf(payParams.get(key)).equals("")) {
                continue;
            }
            sb.append(key).append("=");
            if(encoding){
                sb.append(urlEncode(String.valueOf(payParams.get(key))));
            }else{
                sb.append(String.valueOf(payParams.get(key)));
            }
            sb.append("&");
        }
        sb.setLength(sb.length() - 1);
    }

    public static void buildPayParamsObjNull(StringBuilder sb,Map<String, Object> payParams,boolean encoding){
        List<String> keys = new ArrayList<String>(payParams.keySet());
        Collections.sort(keys);
        for(String key : keys){
            if (payParams.get(key) == null) {
                continue;
            }
            sb.append(key).append("=");
            if(encoding){
                sb.append(urlEncode(String.valueOf(payParams.get(key))));
            }else{
                sb.append(String.valueOf(payParams.get(key)));
            }
            sb.append("&");
        }
        sb.setLength(sb.length() - 1);
    }

    /**
     * @author
     * @param payParams
     * @return
     */
    public static void buildPayParamsObj(StringBuilder sb,Map<String, Object> payParams,boolean encoding,String paramLowType){
        List<String> keys = new ArrayList<String>(payParams.keySet());
        Collections.sort(keys);
        for(String key : keys){
            if (payParams.get(key) == null || String.valueOf(payParams.get(key)).equals("")) {
                continue;
            }
            if(StringUtils.isNotBlank(paramLowType)){
                if(paramLowType.equalsIgnoreCase("up")){
                    sb.append(key.toUpperCase()).append("=");

                }else{
                    sb.append(key.toLowerCase()).append("=");
                }
            }else{
                sb.append(key).append("=");
            }
            if(encoding){
                sb.append(urlEncode(String.valueOf(payParams.get(key))));
            }else{
                sb.append(String.valueOf(payParams.get(key)));
            }
            sb.append("&");
        }
        sb.setLength(sb.length() - 1);
    }





    public static String urlEncode(String str){
        try {
            return URLEncoder.encode(str, "UTF-8");
        } catch (Throwable e) {
            return str;
        } 
    }

    public static String getSuningSign(Map<String,Object> post) {
        String returnstr="";
        Map<String, Object> map = sortMapByKey(post);
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            returnstr+=entry.getKey() + "=" + entry.getValue()+"&";
        }
        return returnstr.substring(0,returnstr.length()-1);
    }

    public static String getSign(Map<String,Object> post,String key) {
        String returnstr="";
        Map<String, Object> map = sortMapByKey(post);
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            returnstr+="&"+entry.getKey() + "=" + entry.getValue();
        }
        return MD5Util.stringMD5(returnstr.substring(1) + "&key=" + key).toLowerCase();
    }

    public static String getSignByNo(Map<String,Object> post,String key) {
        String returnstr="";
        Map<String, Object> map = sortMapByKey(post);
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            returnstr+="&"+entry.getKey() + "=" + entry.getValue();
        }
        return MD5Util.stringMD5(returnstr.substring(1) + "" + key).toLowerCase();
    }

    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, Object> sortMap = new TreeMap<String, Object>(
                new MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;
    }




}

class MapKeyComparator implements Comparator<String>{

    public int compare(String str1, String str2) {
        return str1.compareTo(str2);
    }
}
